import random
import re
from datetime import datetime

from flask import abort
from flask import current_app
from flask import make_response
from flask import request, jsonify
from flask import session

from info import constants, db
from info import redis_store
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blu


@passport_blu.route('/logout')
def logout():
    session.pop('user_id',None)
    session.pop('mobile', None)
    session.pop('nick_name', None)
    session.pop('is_admin',None)

    return jsonify(errno=RET.OK,errmsg='注销成功')


@passport_blu.route('/login',methods=['POST'])
def login():
    params_dict = request.json
    mobile = params_dict.get('mobile')
    password = params_dict.get('password')

    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数有误')

    if not re.match('1[35678]\\d{9}',mobile):
        return jsonify(erron=RET.PARAMERR,errmsg='手机号格式不正确')

    user = None
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DATAERR,errmsg='数据库查询错误')

    if user == None:
        return jsonify(erron=RET.USERERR, errmsg='用户不存在')

    if not user.check_passowrd(password):
        return jsonify(erron=RET.PWDERR, errmsg='密码错误')

    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name

    user.last_login = datetime.now()

    return jsonify(erron=RET.OK,errmsg='登陆成功')





@passport_blu.route('/register',methods=['POST'])
def register():
    params_dict = request.json
    mobile = params_dict.get('mobile')
    smscode = params_dict.get('smscode')
    password = params_dict.get('password')

    if not all([mobile,smscode,password]):
        return jsonify(erron=RET.PARAMERR,errmsg='参数有误')

    if not re.match('1[35678]\\d{9}',mobile):
        return jsonify(erron=RET.PARAMERR,errmsg='手机号格式不正确')

    try:
        real_sms_code = redis_store.get('SMS_' + mobile)
    except Exception as e:

        current_app.logger.error(e)
        return jsonify(erron=RET.DATAERR, errmsg='数据查询失败')

    if not real_sms_code:
        return jsonify(erron=RET.NODATA, errmsg='验证码已过期')

    if real_sms_code != smscode:
        return jsonify(erron=RET.DATAERR, errmsg='验证码输入错误')

    try:
        redis_store.delete('SMS_' + mobile)
    except Exception as e:
        current_app.logger.error(e)

    user = None

    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)

    if user:
        return jsonify(erron=RET.DATAEXIST, errmsg="手机号已注册")
    else:

        user = User()
        user.nick_name = mobile
        user.mobile = mobile
        user.last_login = datetime.now()
        user.password = password

        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(erron=RET.DBERR,errmsg="数据保存失败")


        session['user_id'] = user.id
        session['mobile'] = user.mobile
        session['nick_name'] = user.nick_name

        return jsonify(erron=RET.OK, errmsg="注册成功")


@passport_blu.route('/sms_code',methods=['POST'])
def send_sms_code():
    # 1.参数  手机号，图片验证码，随机值
    params_dict = request.json
    mobile = params_dict.get('mobile')
    image_code = params_dict.get('image_code')
    image_code_id = params_dict.get('image_code_id')

    if not all([mobile,image_code,image_code_id]):
        return jsonify(erron=RET.PARAMERR,errmsg='参数有误')

    if not re.match('1[35678]\\d{9}',mobile):
        return jsonify(erron=RET.PARAMERR,errmsg='手机号格式不正确')

    try:
        real_image_code = redis_store.get("ImageCodeId_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR,errmsg='数据库查询失败')

    if not real_image_code:
        return jsonify(erron=RET.NODATA, errmsg='验证码已过期')

    print(real_image_code.upper())
    print(image_code.upper())

    if real_image_code.upper() != image_code.upper():
        return jsonify(erron=RET.DATAERR, errmsg='验证码不正确')

    sms_code_str = "%06d" % random.randint(0,999999)
    print("验证码是:%s" % sms_code_str)
    result = CCP().send_template_sms(mobile,[sms_code_str, constants.SMS_CODE_REDIS_EXPIRES/60],"1")

    if result != 0:
        return jsonify(erron=RET.THIRDERR,errmsg='发送验证码失败')

    try:
        redis_store.set('SMS_' + mobile,sms_code_str,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR, errmsg='数据保存失败')

    return jsonify(erron=RET.OK, errmsg='发送成功')




@passport_blu.route('/image_code')
def get_image_code():
    # 1. 获取到当前的图片编号id
    image_code_id = request.args.get('imageCodeId',None)

    if not image_code_id:
        return abort(403)

    # 2. 生成验证码
    name,text,image = captcha.generate_captcha()

    current_app.logger.debug("图片验证码内容是:%s" % text)

    try:
        redis_store.set("ImageCodeId_" + image_code_id,text,constants.IMAGE_CODE_REDIS_EXPIRES)

    except Exception as e:
        current_app.logger.error(e)
        abort(500)

    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"
    return response